package mp

import (
	"context"
	"errors"
	pb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
)

type mpUserService struct {
	mpRepo MpRepositoryIface
}

// NewMpUserService
// 构造函数
func NewMpUserService(mpRepo MpRepositoryIface) MpUserServiceIface {
	return &mpUserService{
		mpRepo: mpRepo,
	}
}

// MpLogin
// 获取小程序openid信息
func (s *mpUserService) MpLogin(ctx context.Context, code string) (*MPLoginInfo, error) {
	return s.mpRepo.GetMiniProgramOpenId(ctx, code)
}

// GetMpAccessToken
// 获取accesstoken
func (s *mpUserService) GetMpAccessToken(ctx context.Context) (ak *pb.GetAccessTokenResponse, err error) {
	return s.mpRepo.GetMpAccessToken(ctx)
}

// CleanMpAccessToken 清理缓存
func (s *mpUserService) CleanMpAccessToken(ctx context.Context) error {
	return s.mpRepo.CleanMpAccessToken(ctx)
}

// GetMpMobile
// 获取手机号
func (s *mpUserService) GetMpMobile(ctx context.Context, mobileCode string, encryptedData string, iv string, sessionKey string) (string, error) {
	resp, err := s.mpRepo.GetMpMobile(ctx, &pb.GetMobileRequest{
		MobileCode:    mobileCode,
		EncryptedData: encryptedData,
		Iv:            iv,
		SessionKey:    sessionKey,
	})
	if err != nil {
		return "", err
	}

	if resp == nil {
		return "", errors.New("获取手机号码失败")
	}

	return resp.Mobile, nil
}
